import os
import re

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from .wadeTools_UserJSON import *
from .wadeTools_initDbForTouTiao import *
# Create your views here.
from WebCenter.settings import BASE_DIR

#全局都有一个sql对象,cursor
def initDbConn():
    # dbClass,cursor,conn = initDbConn()
    dbClass = dbClass_toutiao()
    cursor, conn = dbClass.opendb()
    dbClass.initdb(cursor)
    return dbClass,cursor,conn

dbClass,cursor,conn = initDbConn()  #直接占用进程

def saveJson(request):
    #用户提交username和机器号，保存到json数据中
    jsonname = os.path.join(BASE_DIR, 'static\\user.json')
    username = request.GET.get("username")
    machineinfo = request.GET.get("machineinfo")
    print(username)
    print(machineinfo)
    print("接受上传的内容，保存json文件")
    # init读取配置文档，主要获取用户列表和发布次数，获取的日期，如果获取的日期不一样，就清空json文件，重新读取
    USERPOSTNUM = 0
    DataTime = time.strftime('%Y%m%d', time.localtime(time.time()))
    userJson = readjson(jsonname)

    # 检测是否时间一致
    for user in userJson:
        if DataTime != userJson[user][1]:
            # 如果日期不一致，说明又是新的一天，重置清空
            # try:
            #     # 2020.1.20日新增，添加一个功能：将日期不一致的json文件另存
            #     logfilename = os.path.join('historyLog', f'{userJson[user][1]}.json')
            #     savejson(userJson, logfilename)
            # except:
            #     print('保存日志模块失败')
            #     pass

            jsonDateInit(jsonname)
            print('发送记录已过期，已重置')
        else:
            pass
    # 检测是否时间一致END

    # 每接受一次就增加一次发布次数
    try:
        jsonDataAdd(jsonname, username, getUserPOSTNum(username, jsonname) + 1, machineinfo,
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))  # 增加用户
    except:
        jsonDataAdd(jsonname, username, 1, machineinfo,
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))  # 增加用户
    return HttpResponse(username)


def saveToutiao(request):
    #用户提交username和机器号，保存到json数据中
    keyword = request.GET.get("keyword")
    title = request.GET.get("title")
    hasPost = request.GET.get("hasPost")
    print(keyword)
    print(title)
    print(hasPost)
    try:
        re_delWORD = re.compile(r'[《](.*?)[》]', re.S)  # 最小匹配出书名号内容
        delWORD = re.findall(re_delWORD, title)[0]
    except:
        jsondata = {"status": 'error'}
        print(jsondata)
        return JsonResponse(jsondata, safe=False)

    print("接受上传的内容，保存data")
    # init读取配置文档，主要获取用户列表和发布次数，获取的日期，如果获取的日期不一样，就清空json文件，重新读取
    if keyword == '' or title == '' or hasPost =='' or keyword == None or title == None or hasPost == None:
        jsondata = {"status": 'error'}
        print(jsondata)
        return JsonResponse(jsondata, safe=False)

    else:
        dbClass.insertdb(cursor,keyword,title,hasPost)
        # dbClass.closedb(cursor, conn)

        # 构造数据对象
        dblist = getTABLEData()  #查询数据库内容
        jsondata = {"status": 'success',"total": len(dblist), "rows": dblist}

        print(jsondata)

        return JsonResponse(jsondata, safe=False)

def readTouTiao(request):
    #用户提交username和机器号，保存到json数据中
    keyword = request.GET.get("keyword")

    print(keyword)

    print("接受上传的内容，读取数据库")
    # init读取配置文档，主要获取用户列表和发布次数，获取的日期，如果获取的日期不一样，就清空json文件，重新读取

    try:
        resultID,resutTitle = dbClass.getID_By_keyWord(cursor, f'{keyword}')
    except:
        print('库中没有这首歌')
        resultID, resutTitle='查询出错','库中没有这首歌'
    # dbClass.closedb(cursor, conn)
    return HttpResponse(f'{resultID},{resutTitle}')
def test(request):
    jsonList = []
    json1 = {'name': 'jack'}
    json2 = {'name': 'baba'}
    jsonList.append(json1)
    jsonList.append(json2)
    print(jsonList)
    return HttpResponse(str(jsonList))
def hello(request):
    hellomessage = 'welcome to open my web'
    return HttpResponse(hellomessage)

def getUserJSONsFile():
    jsonList = []
    json1 = {'name':'jack'}
    json2 = {'name':'baba'}
    jsonList.append(json1)
    jsonList.append(json2)
    print(jsonList)

def index(request):
    jsonname = os.path.join(BASE_DIR, 'static\\user.json')
    machineNum = [1,2,3]
    showList = []  #二维数组
    userJson = readjson(jsonname)
    machines =[]
    parame = set({}) #设置不重复集合，里面的内容不会重复
    # 检测是否时间一致
    for user in userJson:
        parame.add(userJson[user][2]) #把机器码放到集合里面

        showList.append([user,getUserPOSTNum(user,jsonname)])
    return render(request,'messageBox/index.html', locals())
def admin(request):
    #获取未发送的内容

    result = dbClass.searchdbPostStyle(cursor,0)  #0未发，1垃圾 2复用
    dblist = []
    for row in result:
        print(row)
        dblist.append(list(row))
    # dbClass.closedb(cursor, conn)
    return render(request,'messageBox/admin.html', locals())
def shenhuawade(request):
    urlList =[]
    webURL = 'http://118.24.22.205/messageBox/'
    localURL = 'http://127.0.0.1:8000/messageBox/'
    urlList.append([webURL, 'test','测试页'])
    urlList.append([webURL, 'index','小火花账号每日发帖数'])
    urlList.append([webURL, 'admin','歌曲标题旧版内容'])
    urlList.append([webURL, 'shenhuawade','所有功能后台'])
    urlList.append([webURL, 'saveJson','api保存小火花账号提交接口http://127.0.0.1:8000/messageBox/saveJson/?username=挥发分&machineinfo=778fdd'])
    urlList.append([webURL, 'saveToutiao','api保存头条标题到数据库节接口  http://127.0.0.1:8000/messageBox/saveToutiao/?keyword=挥发分&title=778fdd&hasPost=0'])
    urlList.append([webURL, 'readTouTiao','api 根据某个关键词找出所有符合的标题的一个  http://127.0.0.1:8000/messageBox/readTouTiao/?keyword=你好吗'])
    urlList.append([webURL, 'myajax','新版歌曲标题操作页面，采用ajax技术'])
    urlList.append([webURL, 'myajaxget','api ajax动态获取所有数据库内容接口  http://127.0.0.1:8000/messageBox/myajaxget'])
    urlList.append([webURL, 'myajaxdel','api ajax动态修改某个ID的提交状态为1（已发送） http://127.0.0.1:8000/messageBox/id=5'])
    urlList.append([webURL, 'myajaxDelWord','api 全数据库删除某个关键词，如果删除后，有b与删除前的数据有重复，删除b行内容，保证唯一性 http://127.0.0.1:8000/messageBox/myajaxDelWord?deleteword=xxxx'])
    urlList.append([webURL, 'deletSong','手动删除api接口 全数据库删除某个歌所有title http://127.0.0.1:8000/messageBox/deletSong?songname=xxxx'])
    urlList.append([webURL, 'savesongs','api保存歌曲名字  http://127.0.0.1:8000/messageBox/savesongs?songname=小小鸟'])
    urlList.append([webURL, 'showsongs','api读取歌曲名字 http://127.0.0.1:8000/messageBox/showsongs'])
    urlList.append([webURL, 'myajaxDelWord',''])

    #整合链接和作用
    return render(request,'messageBox/shenhuawade.html', locals())

#修改发送状态为1
def setPostStatus(request):
    ID = request.GET.get("id")

    dbClass.setDbValue(cursor,ID)
    # dbClass.closedb(cursor, conn)

def myajax(request):
    abc = '3'
    return render(request,'messageBox/myajax.html', locals())

def myajaxShowReuse(request):
    return render(request,'messageBox/myajaxShowReuse.html', locals())

def myajaxget(request):  #ajax 返回符合
    # 获取未发送的内容
    result = dbClass.searchdbPostStyle(cursor,0) #0未发，1垃圾 2复用
    dblist = []

    for row in result:
        jsondata = {}
        # print(row)
        jsondata['id'] =list(row)[0]
        jsondata['songname'] =list(row)[1]
        jsondata['title'] =list(row)[2]
        jsondata['haspost'] =list(row)[3]
        dblist.append(jsondata)

    # dbClass.closedb(cursor, conn)

    # jsondata = {"total": 2, "rows": [{ "id": 1, "name": "张三", "age": 18, "address": "北京" }, { "id": 2, "name": "张三", "age": 18, "address": "北京" }]}
    jsondata = {"total": len(dblist), "rows":dblist}
    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict


def getTABLEData():  #ajax 数据库返回构造table内容用的

    # 获取未发送的内容
    result = dbClass.searchdbPostStyle(cursor,2) #0未发，1垃圾 2复用
    dblist = []

    for row in result:
        jsondata = {}
        # print(row)
        jsondata['id'] =list(row)[0]
        jsondata['songname'] =list(row)[1]
        jsondata['title'] =list(row)[2]
        jsondata['haspost'] =list(row)[3]
        dblist.append(jsondata)

    # dbClass.closedb(cursor, conn)

    # jsondata = {"total": 2, "rows": [{ "id": 1, "name": "张三", "age": 18, "address": "北京" }, { "id": 2, "name": "张三", "age": 18, "address": "北京" }]}
    jsondata = {"total": len(dblist), "rows":dblist}
    print(jsondata)
    return jsondata  # 不加safe=False的话必须返回dict


def myajaxgetReuse(request):  #ajax 返回符合
    print("复用标题")
    # 获取未发送的内容
    result = dbClass.searchdbPostStyle(cursor,2) #0未发，1垃圾 2复用
    dblist = []

    for row in result:
        jsondata = {}
        # print(row)
        jsondata['id'] =list(row)[0]
        jsondata['songname'] =list(row)[1]
        jsondata['title'] =list(row)[2]
        jsondata['haspost'] =list(row)[3]
        dblist.append(jsondata)

    # dbClass.closedb(cursor, conn)

    # jsondata = {"total": 2, "rows": [{ "id": 1, "name": "张三", "age": 18, "address": "北京" }, { "id": 2, "name": "张三", "age": 18, "address": "北京" }]}
    jsondata = {"total": len(dblist), "rows":dblist}
    print(jsondata)
    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
def myajaxdel(request):  #返回动态删除数据库id的一行
    # 获取未发送的内容
    print("the GET method")
    ID = request.GET.get("id")
    print(ID)
    jsondata = {"status": 'success'}

    dbClass.setDbValueTo1(cursor,ID)

    # dbClass.closedb(cursor, conn)

    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
def updataTitle(request):  #更新某个id的标题
    # 获取未发送的内容
    print("the GET method")
    ID = request.GET.get("id")
    title = request.GET.get("title")
    print(ID,title)
    if ID == '' or title == '':
        jsondata = {"status": 'error'}
        return JsonResponse(jsondata, safe=False)
    else:
        try:
            dbClass.setDbTitleValue(cursor, ID, title)

            # 构造数据对象
            dblist = getTABLEData()  # 查询数据库内容
            # jsondata = {"status": 'success', "total": len(dblist), "rows": dblist}
            jsondata = {"status": 'success'}
            return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
        except:
            jsondata = {"status": 'error'}
            return JsonResponse(jsondata, safe=False)

    # dbClass.closedb(cursor, conn)


def myajaxdelTo2(request):  #返回动态删除数据库id的一行
    # 获取未发送的内容
    print("the GET method")
    ID = request.GET.get("id")
    print(ID)
    jsondata = {"status": 'success'}

    dbClass.setDbValueTo2(cursor,ID)

    # dbClass.closedb(cursor, conn)

    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict


def myajaxDelWord(request):  #给一个词语，批量删除数据库中的词汇
    print("the GET method")
    deleteword = request.GET.get("deleteword")
    print(deleteword)
    if deleteword == '':
        jsondata = {"status": 'error'}
    else:
        try:
            dbClass.setDbValueTiHuan(cursor,deleteword)
            jsondata = {"status": 'success'}
        except:
            jsondata = {"status": 'error'}

    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
def deletSong(request):  #给一个歌曲，批量删除数据库中的所有该歌曲内容
    print("the GET method")
    deletsong = request.GET.get("songname")
    print(deletsong)
    jsondata = {"status": 'success'}

    dbClass.deletSong(cursor,deletsong)

    jsondata = {"status": '所有数据库中已删除该关键词'}
    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
def savesongs(request):  #，每次把上传库中的歌曲名都上传到网上
    if request.method == 'POST':
        ''' #提交格式魏
        data = {
        'data':['song1','song2']             }
        '''
        try:
            req = json.loads(request.body)
            print(req)
            print(req['data'])
            print(type(req['data']))
            songList = req['data']
        except:
            return JsonResponse({'data': '提交的json格式错误'}, safe=False)  # 不加safe=False的话必须返回dict

    else:
        return JsonResponse({'data':'error,please use Post'}, safe=False)  # 不加safe=False的话必须返回dict

    jsonname = os.path.join(BASE_DIR, 'static\\songs.json')
    userJson = readjson(jsonname)

    for songname in songList:
        try:
            if songname in userJson['data']:
                print("已存在该歌曲")
            else:
                userJson['data'].append(songname)
                savejson(userJson, jsonname)
        except:
            userJson = {'data': []}
            userJson['data'].append(songname)
            savejson(userJson, jsonname)


    jsondata = {"status": 'success'}
    return JsonResponse(jsondata, safe=False)  # 不加safe=False的话必须返回dict
def showsongs(request):  #展示歌曲列表，用于爬虫更新曲库标题使用

    jsonname = os.path.join(BASE_DIR, 'static\\songs.json')
    userJson = readjson(jsonname)

    # jsondata = {"data": userJson}
    return JsonResponse(userJson, safe=False)  # 不加safe=False的话必须返回dict


# 第一步，提交视频批量制作里面的歌曲列表，轮巡reuse内容送来的歌曲名字格式：返回可用的歌曲名，返回完成后，接受已使用请求
def sendMakeMovieSongList(request):  #展示歌曲列表，用于爬虫更新曲库标题使用
    # post方式，传递来数据，返回对应的歌曲内容
    if request.method == 'POST':
        ''' #提交格式魏
        data = {
        'data':['song1','song2']             }
        '''
        try:
            req = json.loads(request.body)
            print(req)
            print(req['data'])
            print(type(req['data']))
            songList = req['data']
            print(songList)
        except:
            return JsonResponse({'data': '提交的json格式错误'}, safe=False)  # 不加safe=False的话必须返回dict

    else:
        return JsonResponse({'data':'error,please use Post'}, safe=False)  # 不加safe=False的话必须返回dict

    # 利用json上传形式获得的歌曲列表
    newTitle=''
    #查询happy的复用列表,查询每一条,返回格式[(18035, '通用', '这首歌火爆了《我爱你》', 2)]
    result = dbClass.searchdbPostStyle(cursor, 2)
    #
    for song in songList: #每首歌都循环一边
        if song != '':
            for row in result:
                print(song)
                title = list(row)[2]  # 这首歌火爆了《我爱你》，现在需要把《》里面的内容替换
                re_delWORD = re.compile(r'[《](.*?)[》]', re.S)  # 最小匹配出书名号内容
                delWORD = re.findall(re_delWORD, title)[0]   #匹配出我爱你，没有书名号
                if delWORD =='':
                    print('书名号中间没有字符串')
                    newTitle = title.replace(f'《》', f'《{song}》')
                else:
                    newTitle = title.replace(f'《{delWORD}》', f'《{song}》')
                print(newTitle)

                #查询是否newTitle是否在reuse中存在
                if dbClass.getID_By_keyWordFromReuse(cursor,newTitle):
                    # 如果存在，继续，如不存在，说明是新的内容，就停止
                    newTitle = ''  #重置标题
                    continue
                else: #如果不存在，说明是新的，可以用
                    #判断下标题长度，如果长度大于30，就忽略
                    if len(newTitle) >30:  #
                        continue
                    else:
                        return JsonResponse({'data': newTitle,'song':song}, safe=False)

    if newTitle == '':  #说明复用表内没有新内容了
        return JsonResponse({'data': 'nonew'}, safe=False)

    # reuse_titleList = []
    #
    # for row in result:
    #     jsondata = {}
    #     # print(row)
    #     jsondata['id'] =list(row)[0]
    #     jsondata['songname'] =list(row)[1]
    #     jsondata['title'] =list(row)[2]
    #     jsondata['haspost'] =list(row)[3]
    #     reuse_titleList.append(jsondata)


    # jsondata = {"data": userJson}
    return JsonResponse({'data': 'error'}, safe=False)
# 第二步，提交视频批量制作里面的歌曲列表，客户端发送标题已经使用的请求，然后把该歌曲加入到reuse表内
def sendMakeMovieSongListHasUsed(request):  #展示歌曲列表，用于爬虫更新曲库标题使用
    # post方式，传递来数据，返回对应的歌曲内容
    if request.method == 'POST':
        ''' #提交格式魏
        data = {
        'data':['song1']             }
        '''
        try:
            req = json.loads(request.body)
            print(req)
            print(req['data'])
            print(type(req['data']))
            hasuseTitle = req['data'][0]
        except:
            return JsonResponse({'data': '提交的json格式错误'}, safe=False)  # 不加safe=False的话必须返回dict
        #把获得title加入到reuse表里面
        dbClass.insertdb_reuse(cursor,'通用',hasuseTitle,2)
        return JsonResponse({'data':'success'}, safe=False)  # 不加safe=False的话必须返回dict


    else:
        return JsonResponse({'data':'error,please use Post'}, safe=False)  # 不加safe=False的话必须返回dict


